<?php
namespace jy_yxkabao;
defined('BY_JYA') or exit('error');
/*
	批次
*/
class batch extends \plugin{
	function add_batch($postdata=array()){
		$goods=pdo_get('jy_yxkabao_list',array('uniacid'=>$_SESSION['uniacid'],'id'=>$postdata['listid']));
		if(!$goods){
			exi('指定卡包不存在！','error');
		}
		$security_codes=$this->add_code($postdata);
		$string='';
		foreach($security_codes as $code){
			$string.=custom_url('jy_yxkabao/item//code='.$code,true)."\r\n";
		}
		if(!$string){
			exi('生成失败！','error');
		}
		$filename = ROOT_AT.random(10).".zip";
		$zip = new \ZipArchive();
		$zip->open($filename,\ZipArchive::CREATE);
		$zip->addFromString('code.txt',$string);
		$zip->close();
		$zip=cfc('files')->source_save($filename,'zip','zip');
		//print_r($zip);exit();
		@unlink($filename);
		$data=array(
			'uniacid'=>$_SESSION['uniacid'],
			'listid'=>$postdata['listid'],
			'workerid'=>$postdata['workerid'],
			'storeid'=>$postdata['storeid'],
			'pluginname'=>$postdata['pluginname'],
			'type'=>$postdata['type'],
			'remark'=>$postdata['remark'],
			'num'=>$postdata['num'],
			'createtime'=>TIMESTAMP,
			'code_file'=>$zip,
			'status'=>1,
		);
		pdo_insert('jy_yxkabao_batch',$data);
		$batchid=pdo_insertid();
		foreach($security_codes as $code){
			$data=array(
				'uniacid'=>$_SESSION['uniacid'],
				'batchid'=>$batchid,
				'listid'=>$postdata['listid'],
				'workerid'=>$postdata['workerid'],
				'storeid'=>$postdata['storeid'],
				'pluginname'=>$postdata['pluginname'],
				'type'=>$postdata['type'],
				'sn'=>$code,
				'createtime'=>TIMESTAMP,
			);
			pdo_insert('jy_yxkabao_batch_code',$data);
		}
		return $zip;	
	}
	function add_code($postdata=array()){
		$daytime = mktime(0,0,0,date('m'),date('d'),date('Y'));
		for($i=1;$i<=$postdata['num'];$i++){
			if(!$postdata['type']){
				$key='00';
			}elseif($postdata['type']==1){
				$key=$postdata['storeid'];
			}elseif($postdata['type']==2){
				$key=$postdata['workerid'];
			}
			$daysnum=date('Ymd',time());
			$sn=$postdata['type'].$key.$_SESSION['uniacid'].$daysnum;
			$code=rand(100000,999999);
			$security_code='NO'.$sn.$code;
			$security_codes[]=$security_code;
		}
		return $security_codes;
	}
}